import axios from "axios";
import {
  showFullScreenLoading,
  hideFullScreenLoading,
} from "@/components/Loading/fullScreen";
import { ElMessage } from "element-plus";

export const baseURL =  import.meta.env.MODE == 'development' ? '/api/' : 'http://81.70.215.143:80/'

console.log(import.meta.env.MODE)

const config = {
  // 默认地址请求地址，可在 .env.** 文件中修改
  baseURL,
  // 设置超时时间
  timeout: 30000,
  // 跨域时候允许携带凭证
  withCredentials: true,
};

const RequestHttp = axios.create(config);

// 请求拦截器配置
const requestInterceptor = (config) => {
  // 当前请求不需要显示 loading，在 api 服务中通过指定的第三个参数: { loading: false } 来控制
  config.loading ?? (config.loading = true);
  config.loading && showFullScreenLoading();
  // if (config.headers && typeof config.headers.set === "function") {
  //   config.headers.set("X-XSRF-TOKEN", getHeader());
  // }
  return config;
};

const responseInterceptor = (response) => {
  const { data } = response;
  // console.log(data)
  // const userStore = useUserStore();
  hideFullScreenLoading();
  // 登录失效
  if (data.code == 401) {
    router.replace('/login');
    ElMessage.error(data.msg);
    return Promise.reject(data);
  }
  // 全局错误信息拦截（防止下载文件的时候返回数据流，没有 code 直接报错）
  if (data.code && +data.code !== 200) {
    ElMessage.error(data.msg);
    return Promise.reject(data);
  }
  // 成功请求（在页面上除非特殊情况，否则不用处理失败逻辑）
  return data;
}

const errorInterceptor = (error) => {
  const { response } = error;
  hideFullScreenLoading();
  if (error.message.indexOf('timeout') !== -1) ElMessage.error('请求超时！请您稍后重试');
  if (error.message.indexOf('Network Error') !== -1) ElMessage.error('网络错误！请您稍后重试');
  if (response) ElMessage.error(response.data.msg);
  // if (!window.navigator.onLine) router.replace('/500');
  return Promise.reject(error);
}

RequestHttp.interceptors.request.use(requestInterceptor, (error) => Promise.reject(error));
RequestHttp.interceptors.response.use(responseInterceptor, errorInterceptor);


const request = {
  get(url, params, _object = {}) {
    return RequestHttp.get(url, { params, ..._object });
  },
  post(url, params, _object = {}) {
    return RequestHttp.post(url, params, _object);
  },
  put(url, params, _object = {}) {
    return RequestHttp.put(url, params, _object);
  },
  delete(url, params, _object = {}) {
    return RequestHttp.delete(url, { params, ..._object });
  },
  downloadByPost(url, params, _object = {}) {
    return RequestHttp.post(url, params, { ..._object, responseType: "blob" });
  },
  downloadByGet(url, params, _object = {}) {
    return RequestHttp.get(url, { params, ..._object }, { responseType: "blob" });
  },
}

export default request;